package com.xmtlxx.web.controller.wms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.xmtlxx.web.controller.wms.service.IViewingService;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.service.ISysOssService;
import com.xmtlxx.wms.domain.bo.ViewingBo;
import com.xmtlxx.wms.domain.bo.ViewingDtlBo;
import com.xmtlxx.wms.domain.vo.ViewingDtlVo;
import com.xmtlxx.wms.domain.vo.ViewingPersonVo;
import com.xmtlxx.wms.domain.vo.ViewingVo;
import com.xmtlxx.wms.service.IViewingDtlService;
import com.xmtlxx.wms.service.IViewingPersonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 看样记录Controller
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Validated
@Api(value = "看样记录控制器", tags = {"看样记录管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/viewing")
public class ViewingController extends BaseController {

    private final IViewingService iViewingService;

    private final IViewingDtlService iViewingDtlService;

    private final IViewingPersonService iViewingPersonService;

    private final ISysOssService ossService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<ViewingVo> initBean(){
        ViewingVo vo = new ViewingVo();
        //可以对数据进行初始化
        return R.ok(vo);
    }

    /**
     * 查询看样记录列表
     */
    @ApiOperation("查询看样记录列表")
//    @SaCheckPermission("wms:viewing:list")
    @GetMapping("/list")
    public TableDataInfo<ViewingVo> list(@Validated(QueryGroup.class) ViewingBo bo, PageQuery pageQuery) {
        return iViewingService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出看样记录列表
     */
    @ApiOperation("导出看样记录列表")
    @SaCheckPermission("wms:viewing:export")
    @Log(title = "看样记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated ViewingBo bo, HttpServletResponse response) {
        List<ViewingVo> list = iViewingService.queryList(bo);
        ExcelUtil.exportExcel(list, "看样记录", ViewingVo.class, response);
    }

    /**
     * 获取看样记录详细信息
     */
    @ApiOperation("获取看样记录详细信息")
//    @SaCheckPermission("wms:viewing:query")
    @GetMapping("/{id}")
    public R<ViewingVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
        ViewingVo vo = iViewingService.queryById(id);
        if(vo.getApplyDay() != null){
            String newDate = format.format(vo.getApplyDay());
            vo.setApplyDayNew(newDate);
        }
        ViewingDtlBo bo = new ViewingDtlBo();
        bo.setViewingId(vo.getId());
        List<ViewingDtlVo> dtlVos = iViewingDtlService.queryList(bo);
        dtlVos.stream().forEach(item->{
            if(vo.getType().equals("1")){
                SysOssBo ossBo = new SysOssBo();
                ossBo.setObjid(item.getId());
                ossBo.setBuss("remote");
                item.setOss(ossService.selectSysOssList(ossBo));
            }
        });
        vo.setItems(dtlVos);

        List<ViewingPersonVo> persons = iViewingPersonService.queryList(id);
        if(persons != null && persons.size() != 0){
            vo.setPersonData(persons);
        }else{
            List<ViewingPersonVo> personList = new ArrayList<>();
            ViewingPersonVo viewingPersonVo = new ViewingPersonVo();
            viewingPersonVo.setName(vo.getName());
            viewingPersonVo.setTel(vo.getTel());
            viewingPersonVo.setIdCard(vo.getIdCard());
            viewingPersonVo.setCardType(vo.getCardType());
            personList.add(viewingPersonVo);
            vo.setPersonData(personList);
        }


        List<SysOss> oss = new ArrayList<>();
        SysOssBo ossBo = new SysOssBo();
        ossBo.setObjid(id);
        List<SysOss> ossList = ossService.selectSysOssList(ossBo);

        List<SysOss> itemsOss = new ArrayList<>();
        List<SysOss> sceneOss = new ArrayList<>();
        List<SysOss> sceneVideo = new ArrayList<>();
        if(ossList != null && ossList.size() > 0){
            List<SysOss> finalOss = oss;
            ossList.stream().forEach(item->{
                switch (item.getBuss()){
                    case "viewing":
                        finalOss.add(item);
                        break;
                    case "viewingDtl":
                        itemsOss.add(item);
                        break;
                    case "viewingCenter":
                        vo.setCenterSign(item.getFileName());
                        vo.setCenterTime(item.getCreateTime());
                        break;
                    case "viewingSign":
                        vo.setSigns(item.getFileName());
                        vo.setSignsTime(item.getCreateTime());
                        break;
                    case "scenePicture":
                        if(item.getFileSuffix().toLowerCase().equals("mp4") || item.getFileSuffix().toLowerCase().equals(".mp4")){
                            sceneVideo.add(item);
                        }else{
                            sceneOss.add(item);
                        }
                        break;
                }
            });
        }
        vo.setItemsOss(itemsOss);
        vo.setOss(oss);
        vo.setSceneOss(sceneOss);
        vo.setSceneVideo(sceneVideo);
        return R.ok(vo);
    }

    /**
     * 新增看样记录
     */
    @ApiOperation("新增看样记录")
    @SaCheckPermission("wms:viewing:add")
    @Log(title = "看样记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ViewingVo vo) {
        ViewingBo bo = new ViewingBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iViewingService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改看样记录
     */
    @ApiOperation("修改看样记录")
    @SaCheckPermission("wms:viewing:edit")
    @Log(title = "看样记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ViewingVo vo) {
        ViewingBo bo = new ViewingBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iViewingService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 修改看样记录
     */
    @ApiOperation("阅证操作")
    @SaCheckPermission("wms:viewing:edit")
    @Log(title = "看样记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/viewing")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> viewing(@Validated(EditGroup.class) @RequestBody ViewingVo vo) {
        ViewingBo bo = new ViewingBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iViewingService.updateViewingByBo(bo) ? 1 : 0);
    }


    /**
     * 修改看样记录
     */
    @ApiOperation("看样审核")
    @SaCheckPermission("wms:viewing:edit")
    @Log(title = "看样记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping("/check")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> check(@Validated(EditGroup.class) @RequestBody ViewingVo vo) {
        ViewingBo bo = new ViewingBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iViewingService.updateViewingByEnty(bo) ? 1 : 0);
    }

    /**
     * 删除看样记录
     */
    @ApiOperation("删除看样记录")
    @SaCheckPermission("wms:viewing:remove")
    @Log(title = "看样记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iViewingService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }
}
